from dataclasses import field, dataclass
from typing import Any

from flask import jsonify

from .http_code import HttpCode


@dataclass
class Response:
    code: HttpCode.SUCCESS
    message: str = ""
    data: Any = field(default=dict)


def json(data: Response = None):
    """基础响应数据接口"""
    return jsonify(data), 200


def success_json(data: Any = None):
    """成功响应数据接口"""
    return json(Response(code=HttpCode.SUCCESS, message="", data=data))


def fail_json(data: Any = None):
    """失败响应数据接口"""
    return json(Response(code=HttpCode.FAIL, message="", data=data))


def validate_error_json(errors: dict = None):
    """校验错误响应数据接口"""
    first_key = next(iter(errors))
    if first_key is not None:
        msg = errors.get(first_key)[0]
    else:
        msg = ""
    return json(Response(code=HttpCode.VALIDATE_ERROR, message=msg, data=errors))


def message(code: HttpCode, msg: str = ""):
    """基础消息响应"""
    return json(Response(code=code, message=msg, data={}))


def success_message(msg: str = ""):
    """成功消息响应接口"""
    return json(Response(code=HttpCode.SUCCESS, message=msg, data={}))


def fail_message(msg: str = ""):
    """失败消息响应接口"""
    return json(Response(code=HttpCode.FAIL, message=msg, data={}))


def not_found_message(msg: str = ""):
    """未找到消息响应接口"""
    return json(Response(code=HttpCode.NOT_FOUND, message=msg, data={}))


def unauthorized_message(msg: str = ""):
    """未授权消息响应接口"""
    return json(Response(code=HttpCode.UNAUTHORIZED, message=msg, data={}))


def forbidden_message(msg: str = ""):
    """禁止访问消息响应接口"""
    return json(Response(code=HttpCode.FORBIDDEN, message=msg, data={}))
